package com.bid.base.common.util;

import com.alibaba.fastjson.JSONObject;
import com.bid.base.common.response.ApiResult;
import com.bid.base.common.response.ErrorCode;
import com.bid.base.common.util.sm4.Sm4Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * <strong>Description : </strong> <br>
 * <p>
 * <strong>北京正源德标科技信息有限责任公司</strong> <br>
 * </p>
 * <br>
 *
 * @author : zhaots
 * @date Date : 2020年12月28日 16:05
 * 修改人 修改日期 修改描述<br>
 * -------------------------------------------<br>
 *     https://blog.csdn.net/justry_deng/article/details/81042379
 * <br>
 * <br>
 */
@Slf4j
public class CommonHttp {

    public static boolean requestSucc(ApiResult<?> res) {
        if(Stringer.isNullOrEmpty(res)){
            log.info("响应为空");
            return false;
        }
        if(res.getStatus() == ErrorCode.SUCCESS.getStatus() || res.getStatus() == ErrorCode.TOKEN_REFRESH.getStatus()){
            return true;
        }
        log.error("request-fail 请求失败：  \t "+JSONObject.toJSONString(res));
        return false;
    }

    public static void main(String[] args) {
        String sm4Key = "911E32949D98B79FC5D7CD010FBD897C";
        System.out.println("响应状态为start:");
//        String url = "http://localhost:8001/api/oauth2/refresh_token1";
        String url = "https://localdevwechatpay.fair-bidding.com/api/oauth2/refresh_token1";
//        url = "http://10.10.80.48:8001/api/oauth2/refresh_token1";
        HashMap<String, String> params = new HashMap<>();
        params.put("k1","v1");
        params.put("k3","v3");

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("h1","value");
        String s = CommonHttp.postEncrypt(url, params,sm4Key,headerParams);
        System.out.println("返回结果:" + s);
    }

    /**
     * 方法调用 替换了 HttpClient ->CloseableHttpClient
     * //        HttpClient httpClient = new DefaultHttpClient();
     *         CloseableHttpClient httpClient = HttpClientBuilder.create().build();
     *
     *         //        HttpResponse response = null;
     *         CloseableHttpResponse response = null;
     * @param url
     * @param paramsMap
     * @return
     */
    public static String postEncrypt(String url, Map<String, String> paramsMap,String sm4Key,Map<String, String> headerMap) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        //添加header
        if(!Stringer.isNullOrEmpty(headerMap)){
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                httpPost.addHeader((String) entry.getKey(),  (String) entry.getValue());
            }
        }
        //添加body
        ByteArrayEntity entity = null;
        try {
            String deStr = "";
            if(!Stringer.isNullOrEmpty(paramsMap)){
                Object o = JSONObject.toJSON(paramsMap);
                deStr = Sm4Util.encryptEcb(sm4Key, o.toString());
            }
            log.info("加密之后的数据是： "+ deStr);
            entity = new ByteArrayEntity(deStr.getBytes("UTF-8"));
            entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        } catch (Exception e) {
            log.error("向服务器承保接口发起http请求,封装请求body时出现异常", e);
            throw new RuntimeException("向服务器承保接口发起http请求,封装请求body时出现异常", e);
        }
        httpPost.setEntity(entity);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //连接超时时间
                .setConnectionRequestTimeout(1000) //从连接池中取的连接的最长时间
                .setSocketTimeout(10 *1000) //数据传输的超时时间
                .setStaleConnectionCheckEnabled(true) //提交请求前测试连接是否可用
                .build();
        httpPost.setConfig(config);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            log.error("提交给服务器的请求，不符合HTTP协议", e);
            throw new RuntimeException("提交给服务器的请求，不符合HTTP协议", e);
        } catch (IOException e) {
            log.error("向服务器承保接口发起http请求,执行post请求异常", e);
            throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
        }finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 没有测试 注意
     */
    public static String postCommon(String url, Map<String, String> paramsMap) {

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 参数
        HttpPost httpPost = new HttpPost(url);
        try {
            if (!Stringer.isNullOrEmpty(paramsMap)) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    params.add(new BasicNameValuePair((String) entry.getKey(),
                            (String) entry.getValue()));
                }
                httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        // 创建Post请求

        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                return EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


}
